const swapTrade = async(browser, page) => {
    try {
        await page.goto('https://testnet.zenithfinance.xyz/swap');
        await page.waitForTimeout(2000); // 等待2秒
        const Connect = await page.locator("xpath=//button[text()='Connect']").all();
        if (Connect.length > 0){
            await page.waitForTimeout(2000);
            // 操作新页面中的 'MetaMask
            const [xhlLoginpage] = await Promise.all([
                browser.waitForEvent('page', {timeout:240000}), // 等待新窗口打开
                page.locator("xpath=//div[text()='MetaMask']").click(),
                console.log('点击钱包')
            ]);
            // 等待新页面加载
            await xhlLoginpage.waitForLoadState('networkidle', {timeout:240000});
            if (xhlLoginpage){
                console.log('新页面加载完成')
                await xhlLoginpage.locator('xpath=//button[@data-testid="confirm-btn"]').click();
                console.log("连接成功")
            }
        } else {
            console.log('已经连接钱包')
        }
        await page.locator("xpath=//span[text()='Select token']").click();
        await page.locator("xpath=//div[@data-testid='common-base-USDC']/div[text()='USDC']").click();
        await page.locator("xpath=//input[@id='swap-currency-input']").fill('0.1');
        await page.locator("xpath=//button/div[text()='Swap']").click({timeout:60000})
        const [xhlLoginpage] = await Promise.all([
            browser.waitForEvent('page', {timeout:240000}), // 等待新窗口打开
            page.locator("xpath=//div[text()='Confirm swap']").click(),
            console.log('点击钱包')
        ]);
        // 等待新页面加载
        await xhlLoginpage.waitForLoadState('networkidle', {timeout:240000});
        if (xhlLoginpage){
            console.log('新页面加载完成')
            await xhlLoginpage.locator("xpath=//button[@data-testid='confirm-footer-button']").click();
            console.log("确认交易请求")
        }
    } catch (err) {
        console.error(err);
    }
};

module.exports = { swapTrade };